<!--
 * @描述: 
 * @作者: 约訂
 * @Date: 2024-10-14 15:00:44
 * @LastEditTime: 2024-11-22 14:16:54
 * @修改人员: 约訂
-->
<template>
  <div class="common-layout main">
    <el-container>
      <el-aside width="450px">
        <el-header class="center_flex first_header">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="flex_box">
            <el-avatar shape="square" :size="50" :src="infoData.avatar" />
            <div class="mal_10">
              <div class="flex_box font_w">
                {{ userData.TrueName ? userData.TrueName : "- - - -" }}
              </div>
              <div class="flex_box font_12">
                在线客服管理系统V 1.0
                <!-- <el-button
                  type="danger"
                  size="small"
                  style="margin-left: 20px"
                  @click="Database"
                  >清空缓存</el-button
                > -->
              </div>
            </div>
            <!-- style="height: var(--ep-menu-item-height)" -->
            <div class="type_day" color="$ep-color-primary">
              <i inline-flex i="dark:ep-moon ep-sunny " @click="toggleDark()" />
            </div>
            <!-- <button
              class="border-none w-full bg-transparent cursor-pointer"
            ></button> -->
          </el-col>
        </el-header>
        <el-row class="group_list">
          <el-col
            :xs="24"
            :sm="24"
            :md="24"
            :lg="24"
            :xl="24"
            class="state_list"
          >
            <!-- <div class="grid-content ep-bg-purple" /> -->
            <el-radio-group v-model="radio" @change="GetGroundList()">
              <el-radio :value="-1">查看全部</el-radio>
              <el-radio :value="1">只看厂商</el-radio>
              <el-radio :value="2">只看师傅</el-radio>
              <el-radio :value="0">未配置</el-radio>
            </el-radio-group>
            <el-input
              v-model="defaultData.Content"
              style="width: 94%"
              placeholder="请输入群名称"
              @keyup.enter="GetGroundList()"
            >
              <template #prefix>
                <el-icon class="el-input__icon"><Search /></el-icon>
              </template>
            </el-input>
            <!-- <el-autocomplete
              v-model="state1"
              :fetch-suggestions="querySearch"
              clearable
              class="inline-input w-15"
              placeholder="Please Input"
              @select="handleSelect"
            /> -->
          </el-col>
          <el-col
            :xs="12"
            :sm="12"
            :md="12"
            :lg="12"
            :xl="12"
            class="group_chats"
            @scroll="CloseMenu"
          >
            <div
              v-for="(item, index) in groupChatsList"
              :key="'group_' + index"
              class="flex_box group_box box_border_hover"
              @click.stop="ActiveGroup(item)"
              :class="item.open ? 'active_group' : ''"
              @contextmenu.prevent="ShowContextMenu($event, item)"
            >
              <div class="headshot">
                <el-badge
                  :value="item.NotReadCount"
                  :max="99"
                  class="item"
                  v-if="item.NotReadCount > 0"
                >
                  <el-avatar
                    shape="square"
                    fit="cover"
                    :size="40"
                    :src="ParseUrl(item)"
                  />
                </el-badge>
                <el-avatar
                  v-else
                  shape="square"
                  fit="cover"
                  :size="40"
                  :src="ParseUrl(item)"
                />
              </div>
              <div class="group_info">
                <div class="group_name">
                  {{ item.GroupName }}
                </div>
                <div
                  class="not_answer_count font_12"
                  v-if="item.NotAnswerCount > 0"
                >
                  有{{ item.NotAnswerCount }}条消息未回复
                </div>
                <!-- <div class="not_answer_count" v-else>
                  
                </div> -->
              </div>
            </div>
            <!-- <div class="grid-content ep-bg-purple" /> -->
          </el-col>
          <el-col
            :xs="12"
            :sm="12"
            :md="12"
            :lg="12"
            :xl="12"
            class="user_list"
            v-loading="loadingUser"
          >
            <div
              class="flex_box group_box box_border_hover"
              @click="GetUserMsg(groupActive)"
              v-if="groupActive?.open"
              :class="
                userActive?.row?.QuestionUserId == -1 ? 'active_group' : ''
              "
            >
              <div class="headshot">
                <!-- <el-badge
                  :value="groupActive.NotReadCount"
                  :max="99"
                  class="item"
                  v-if="groupActive.NotReadCount > 0"
                >
                  <el-avatar
                    shape="square"
                    fit="cover"
                    :size="40"
                    :src="ParseUrl(groupActive)"
                  />
                </el-badge> -->
                <el-avatar
                  shape="square"
                  fit="cover"
                  :size="40"
                  :src="ParseUrl(groupActive)"
                />
              </div>
              <div class="group_info">
                <div class="group_name">
                  {{ groupActive.GroupName }}
                </div>
                <!-- <div
                  class="not_answer_count font_12"
                  v-if="groupActive.NotAnswerCount > 0"
                >
                  有{{ groupActive.NotAnswerCount }}条消息未回复
                </div> -->
                <!-- <div class="not_answer_count" v-else>
                  
                </div> -->
              </div>
            </div>
            <div
              v-for="(item, index) in groupActive.userList"
              :key="'group_' + index"
              class="flex_box group_box box_border_hover"
              @click="GetUserMsg(item)"
              :class="item.open ? 'active_group' : ''"
            >
              <div class="headshot">
                <el-badge
                  :value="item.NotReadCount"
                  :max="99"
                  class="item"
                  v-if="item.NotReadCount > 0"
                >
                  <el-avatar
                    shape="square"
                    fit="cover"
                    :size="40"
                    :src="item.SendUserAvatar"
                  />
                </el-badge>
                <el-avatar
                  v-else
                  shape="square"
                  fit="cover"
                  :size="40"
                  :src="item.SendUserAvatar"
                />
              </div>
              <div class="group_info">
                <div class="group_name">
                  {{ item.SendUserName }}
                </div>
                <div
                  class="not_answer_count font_12"
                  v-if="item.NotAnswerCount > 0"
                >
                  有{{ item.NotAnswerCount }}条消息未回复
                </div>
                <!-- <div class="not_answer_count" v-else>
                  
                </div> -->
              </div>
            </div>
            <!-- <div class="grid-content ep-bg-purple" /> -->
          </el-col>
        </el-row>
      </el-aside>
      <el-container>
        <el-header class="top_name_group">
          <div class="group_name">
            {{ groupActive.GroupName }}
            <span v-if="userActive?.row?.SendUserName">
              ：《
              <span class="send_user_name">{{
                userActive?.row?.SendUserName
              }}</span>
              》
            </span>
          </div>
          <div
            class="group_notAnswerCount"
            v-if="statisticsAll?.DockingUserList?.length"
          >
            本群共{{
              statisticsAll?.DockingUserList?.length
                ? statisticsAll?.DockingUserList?.length
                : 0
            }}个对接客服：<span
              v-for="(item, index) in statisticsAll?.DockingUserList"
              class="customer_name"
              :key="item.UserId"
              >{{ item.TureName }}</span
            >
          </div>
        </el-header>
        <el-main
          ><Chat
            :groupChatsList="userActive"
            :infoData="infoData"
            :userData="userData"
            @GetOldData="GetOldData"
            v-if="userActive?.row"
            ref="chatItemAll"
          ></Chat
        ></el-main>
        <!-- <div class="">
          
        </div> -->
      </el-container>
      <el-aside width="260px" class="end_aside">
        <el-header class="center_flex first_header end_header">
          <div
            class="statistics_all"
            v-if="statisticsAll?.DockingUserList?.length"
          >
            <span>今日共接待{{ statisticsAll.TodayReceptCount }}个客户</span>
            <span>累积处理{{ statisticsAll.TotalDealCount }}条消息</span>
            <span>今日有{{ statisticsAll.TodayNoDealCount }}条消息未处理</span>
          </div>
        </el-header>
        <el-row class="group_main_info group_list" v-loading="loadingUser">
          <div class="interior_item" v-if="groupAllNumber != 0">
            <div class="list_col">群成员 · {{ groupAllNumber }} （人）</div>

            <div class="i_list">
              <div class="title">内部成员</div>
              <!-- {{ groupUserListInterior }} -->
              <div
                v-for="(item, index) in groupUserListInterior"
                class="user_item"
              >
                <img
                  v-if="item.online"
                  src="https://xigyubucket.oss-cn-hangzhou.aliyuncs.com/2024-11-14/ejB31He9aUPijPz9ek0a8kk3Z4dP8.jpg"
                  alt=""
                />
                <img
                  v-else
                  src="https://xigyubucket.oss-cn-hangzhou.aliyuncs.com/2024-11-14/8ayx09mI021ZX3jE6t3E71XNlf8H4.jpg"
                  alt=""
                />
                <span class="max_user_text">{{ item.UserName }}</span>
              </div>
              <div>- - - - - - - - - - - - - - - - - -</div>
              <div class="title">外部成员</div>
              <div
                v-for="(item, index) in groupUserListExterior"
                class="user_item"
              >
                <img
                  src="https://xigyubucket.oss-cn-hangzhou.aliyuncs.com/2024-11-14/8ayx09mI021ZX3jE6t3E71XNlf8H4.jpg"
                  alt=""
                />
                <span class="max_user_text">{{ item.UserName }}</span>
              </div>
            </div>
            <!-- <div class="i_list">
              
            </div> -->
          </div>
        </el-row>
      </el-aside>
    </el-container>
    <div
      v-show="contextMenuVisible"
      class="custom-context-menu"
      ref="contextFocus"
      :groupItem="groupItem"
      @click.stop="contextMenuVisible = true"
      :style="{
        top: contextMenuY,
        left: contextMenuX,
      }"
      @blur="CloseCustom"
    >
      <RightClickMenu :groupItem="groupItem" ref="clickMenu"></RightClickMenu>
    </div>
  </div>

  <!-- <RightClickMenu></RightClickMenu> -->
</template>
<script setup lang="ts">
import { toggleDark } from "~/composables";
import { ref, reactive, getCurrentInstance, watch } from "vue";
/**聊天组件 */

import Chat from "./indexSub/chat.vue";

import RightClickMenu from "./indexSub/rightClickMenu.vue";
/**element - push 图标 */
import { Calendar, Search } from "@element-plus/icons-vue";
import {
  closeWebSocket,
  initWebSocket,
  sendWebSocket,
  isConnected,
} from "../../../utils/websocket";
import {
  openDatabase,
  createNewObjectStore,
  saveChatMessage,
  saveAllChatMessage,
  getChatHistory,
  deleteDatabase,
} from "../../../utils/database";
import {
  SocketTypeEnum,
  findEnumNameByValue,
  ToWhomAll,
} from "../../../utils/socketTypeEnum";
import { correspondingUser, debounce, reviseState, examineList } from "./index";
import { webpackUrl } from "../../../utils/urlAll";
import { nextTick } from "process";
import { log } from "console";
const { proxy } = getCurrentInstance() as any;
const defaultData = ref<any>({
  SendCoworker: 0,
  IsAnswer: -1,
  Content: "",
  IsBind: -1,
});
/** */
const radio = ref<any>(-1);
/**用户信息 */
const userData = ref<any>({
  Id: "",
  TrueName: "- - - -",
  UserId: "- - - -",
});
/**解析返回头像 */
const ParseUrl = (row: any) => {
  let src =
    "https://xigyubucket.oss-cn-hangzhou.aliyuncs.com/2024-10-24/YOT07ib20073N6F463884u39y242I.png";
  if (row.GroupType == 1) {
    src =
      "https://xigyubucket.oss-cn-hangzhou.aliyuncs.com/2024-11-12/gOnQT0Q9Al91QK5420Z13P80E0HYo.png";
  } else if (row.GroupType == 2) {
    src =
      "https://xigyubucket.oss-cn-hangzhou.aliyuncs.com/2024-11-12/u9OKV24v0N47f62x39avxBHA83C2K.png";
  } else if (row.GroupType == 0) {
  }
  return src;
};
/** */
/**右键自定义开关 */
const contextMenuVisible = ref<boolean>(false);
// 记录菜单位置
const contextMenuX = ref<any>(0);
const contextMenuY = ref<any>(0);
/**右键菜单组件 */
const contextFocus = ref<any>(null);
/**右键内容 */
const groupItem = ref<any>({});
const clickMenu = ref<any>(null);
/***右键自定义功能 */
const ShowContextMenu = async (event: any, item: any) => {
  if (userData.value.IsAdmin != 1) {
    return;
  }
  event.preventDefault();
  // console.log(event);
  console.log(event);
  let num = 0;
  if (window.innerHeight - event.clientY < 440) {
    num = 440;
  }
  // await nextTick();
  contextMenuX.value = event.clientX + "px";
  contextMenuY.value = event.clientY - num + "px";
  // console.log(contextMenuX.value, contextMenuY.value);
  contextMenuVisible.value = true;
  groupItem.value = item;
  // await nextTick();
  clickMenu.value.GetGroup(item);
  // setTimeout(() => {
  //   console.log(contextFocus.value.focus());
  // }, 2000);
  // setInterval(() => {
  //   contextMenuX.value += 20;
  // });
};
const CloseMenu = () => {
  contextMenuVisible.value = false;
};
watch(
  () => contextMenuVisible.value,
  (newValue, oldValue) => {
    if (contextMenuVisible.value) {
      document.body.addEventListener("click", CloseMenu);
    } else {
      document.body.removeEventListener("click", CloseMenu);
    }
  }
);
// const CloseCustom = () => {
//   console.log("失焦了");
// };
// };
/**搜索参数 */
const search = ref<any>({
  user: "",
});
/**请求唯一标识 */
const UUID = ref<any>(null);
/**所有群 */
const groupChatsList = ref<any[]>([]);
/**选中的群 */
const groupActive = ref<any>({
  userList: [],
});
/**被选中的群对应的所有群成员 */
// const userList = ref<any[]>([]);
/**被选中的群成员 */
const userActive = ref<any>({});
/**初始化基础信息 */
const infoData = ref<any>({
  /**版本号 */
  version: 1,
  /**头像 */
  avatar:
    "https://xigyubucket.oss-cn-hangzhou.aliyuncs.com/2024-10-24/YOT07ib20073N6F463884u39y242I.png",
});
/**聊天框组件 */
const chatItemAll = ref<any>(null);
/**连接websokect */
const ConnectMsg = async () => {
  // 获取查询参数
  const queryString = window.location.search;
  // 创建 URLSearchParams 对象
  const params = new URLSearchParams(queryString);
  // 获取 chatuser 的值
  const chatuser = params.get("chatuser");
  console.log(chatuser);
  console.log(encodeURI(chatuser).replace(/\+/g, "%2B"));
  const token = chatuser;
  proxy.$store.commit("setToken", token);
  const toIp = webpackUrl + `?token=${token}`;
  initWebSocket(toIp);
};
/**获取群组 */
const GetGroundList = async () => {
  if (isTrueAll.value) {
    groupActive.value = {
      userList: [],
    };
    userActive.value = {};
    statisticsAll.value = {};
    groupAllNumber.value = 0;
  }

  let { rows, Success } = await proxy.$Post(
    "/DealWeChatRecord/WeChatRecordGroupPageList",
    {
      Page: 1,
      Rows: 1000,
      FactoryId: -1,
      /**默认不查询本企业的企业账号消息0  全部：-1 */
      SendCoworker: defaultData.value.SendCoworker,
      Content: defaultData.value.Content,
      IsBind: defaultData.value.IsBind,
      UserId: userData.value.UserId,
      GroupType: radio.value,
      // Content:"",
    }
  );
  if (!Success) return;
  console.log(rows);
  let isClose = false;
  rows.Data.forEach((element: any, index: number) => {
    if (element.GroupInfoId == groupActive.value?.GroupInfoId) {
      element.open = groupActive.value.open;
      element.userList = groupActive.value.userList;
      isClose = true;
    } else {
      element.open = false;
      element.userList = [];
    }
  });
  groupChatsList.value = rows.Data;
  if (!isClose) {
    groupActive.value = {
      userList: [],
    };
  }
};
const isTrueAll = ref<boolean>(true);
/**获取所有群聊信息 */
const GetGround = (time: number = 5000, isTrue: boolean = true) => {
  isTrueAll.value = isTrue;
  debounce(GetGroundList, {}, 5000)();
};
/** */
const numberAll = ref<number>(0);
/**整合接受消息方法 */
const GetWsMessage = () => {
  proxy.$bus.on("wsMessage", async (data: any) => {
    // console.log("触发总线回执", data);
    const msgData = data;

    // console.log(msgData);
    /**接受消息 */
    /**用户信息类型 */
    if (msgData.Type == SocketTypeEnum.FacTitle) {
      //用户信息赋值
      userData.value = msgData.data;
      /**存入基础数据 */
      if (!localStorage.getItem(userData.value.UserId)) {
        // console.log("正在存入数据");

        localStorage.setItem(
          userData.value.UserId,
          JSON.stringify(infoData.value)
        );
      } else {
        /**更新数据 */
        infoData.value = JSON.parse(
          localStorage.getItem(userData.value.UserId) || ""
        );
      }

      openDatabase(userData.value.UserId);
      //获取所有群信息
      GetGround();
    } else if (msgData.Type == SocketTypeEnum.RoomTitle) {
      let list = msgData.data.Data;
      createNewObjectStore(list, "GroupInfoId");
      /**给群列表添加开关以及群成员 */
      let isClose = false;
      list.forEach((element: any, index: number) => {
        if (element.GroupInfoId == groupActive.value?.GroupInfoId) {
          element.open = groupActive.value.open;
          element.userList = groupActive.value.userList;
          isClose = true;
        } else {
          element.open = false;
          element.userList = [];
        }
      });
      groupChatsList.value = list;
      if (!isClose) {
        groupActive.value = {
          userList: [],
        };
      }

      userActive.value = {};
    } else if (msgData.Type == SocketTypeEnum.RoomUser) {
      if (msgData.data.UUID == UUID.value.split(","[0])) {
        let list = msgData.data.Data;
      }
      // userList.value = list;
    } else if (msgData.Type == SocketTypeEnum.RoomChat) {
      if (msgData.data.UUID.split(",")[0] == UUID.value.split(",")[0]) {
        /**获取当前成员数据信息 */
        let list = msgData.data.Data;

        let user =
          groupChatsList.value[groupActive.value.index].userList[
            userActive.value?.index
          ];

        /**本地存储的数据 */
        list.reverse();

        if (list.length != 0) {
          if (UUID.value.split(",")[1] == 0 || UUID.value.split(",")[1] == 2) {
            if (user.list.length == 0) {
              user.list = list;
              // user.list = locationUser.list;
              chatItemAll.value.scrollToBottom(user.QuestionUserId, 0);
              console.log("到这了");
            } else {
              user.list = list.concat(user.list);
              chatItemAll.value.scrollToBottom(
                groupActive.value.userList[userActive.value.index]
                  .QuestionUserId,
                0,
                800
              );
            }
          } else {
            console.log("新消息插入");

            let userAll = userActive.value.list;

            user.list = user.list.concat(list);
          }
          console.log(user.list);
        }
      }
    } else if (msgData.Type == SocketTypeEnum.RecordMsg) {
      numberAll.value++;
      console.log(numberAll.value);

      // console.log(msgData.data);
      /**获取被选中的用户 */
      let user = userActive.value?.row || {
        QuestionUserId: -1,
      };
      let itemMsg = msgData.data;
      console.log(user, user.GroupInfoId, itemMsg.GroupInfoId);
      if (
        user.GroupInfoId == itemMsg.GroupInfoId &&
        user?.QuestionUserId == -1
      ) {
        console.log("收到的群消息", itemMsg);
        userActive.value?.list.push(itemMsg);
        chatItemAll.value.ScrollToBottomNew();
      } else {
        /**检验是否是这个窗口 */
        if (
          user.GroupInfoId == itemMsg.GroupInfoId &&
          user?.QuestionUserId == itemMsg.QuestionUserId
        ) {
          userActive.value?.list.push(itemMsg);

          chatItemAll.value.ScrollToBottomNew();
        }
        // console.log("");

        GetGround(5000, false);

        if (
          groupActive.value?.open &&
          groupActive.value?.GroupInfoId == itemMsg.GroupInfoId &&
          user?.QuestionUserId != -1
        ) {
          console.log("进来了");

          ActiveGroup(groupActive.value, false);
        }
      }
    } else if (msgData.Type == SocketTypeEnum.AnswerMsg) {
      let data = msgData.data;

      /**获取被选中的用户 */
      let user = userActive.value;
      console.log(user, data);

      if (
        user.row.GroupInfoId == data.GroupInfoId &&
        user?.row.QuestionUserId == -1
      ) {
        console.log("收到的群消息", data);
        userActive.value?.list.push(data);

        chatItemAll.value.ScrollToBottomNew();
      } else {
        /**检验是否是这个窗口 */
        if (user?.row?.QuestionUserId == data.QuestionUserId) {
          user.list.push(data);
          user.list.some((element: any) => {
            if (element.Id == data.QuestionId && element.Record == 1) {
              element.IsAnswer = 1;
              console.log("修改的对象", element);

              return true;
            }
          });
          chatItemAll.value.ScrollToBottomNew();
        }
      }
    }
  });
};
const loadingUser = ref<any>(false);
/**群成员信息-内部 */
const groupUserListInterior = ref<any>([]);
/**外部成员 */
const groupUserListExterior = ref<any[]>([]);
/**群总人数 */
const groupAllNumber = ref<number>(0);
/**统计数据 */
const statisticsAll = ref<any>({});
/**选中群并且获取此群下面的成员信息 */
const ActiveGroup = async (itemGroup: any, loading: boolean = true) => {
  groupActive.value = itemGroup;
  let oldId = userActive.value.row?.GroupInfoId;

  if (userActive.value.row?.GroupInfoId != itemGroup.GroupInfoId) {
    userActive.value = {};
  }
  groupChatsList.value.forEach((element: any, index: any) => {
    if (itemGroup.GroupInfoId == element.GroupInfoId) {
      element.open = true;
      groupActive.value.index = index;
    } else {
      element.open = false;
    }
  });

  loadingUser.value = loading;
  /**群成员 */
  let { rows, Success } = await proxy.$Post(
    "/DealWeChatRecord/WeChatRecordGroupMemberPageList",
    {
      Page: 1,
      Rows: 1000,
      GroupInfoId: itemGroup.GroupInfoId,
      GroupName: itemGroup.GroupName,
      /**默认不查询本企业的企业账号消息0  全部：-1 */
      SendCoworker: defaultData.value.SendCoworker,
      IsAnswer: defaultData.value.IsAnswer,
      UserId: userData.value.UserId,
      UUID: "6666",
      // Content:"",
    }
  );
  if (!Success) return;

  // console.log(groupActive.value.userList, rows.Data);
  groupActive.value.userList = await correspondingUser(
    groupActive.value.userList,
    rows.Data,
    oldId,
    itemGroup.GroupInfoId
  );
  /**内部成员 */
  let data = await proxy.$Post(
    "/DealWeChatRecord/WeChatRecordGroupMemberInfoPageList",
    {
      Page: 1,
      Rows: 1000,
      GroupInfoId: itemGroup.GroupInfoId,
      GroupName: itemGroup.GroupName,

      SendCoworker: 1,
      IsAnswer: defaultData.value.IsAnswer,
      UserId: userData.value.UserId,
    }
  );
  if (!data.Success) return;
  /**在线成员 */
  let itemAll = await proxy.$Post("/DealWeChatRecord/GetOnlineUser", {
    GroupInfoId: itemGroup.GroupInfoId,
    UserId: userData.value.UserId,
  });
  if (!itemAll.Success) return;
  console.log("内部", itemAll.rows);
  data.rows.MemberList.forEach((item: any, index: any) => {
    item.online = false;
    for (let index = itemAll.rows.length - 1; index >= 0; index--) {
      // console.log(item.CustomerUserId, itemAll.rows[index].UserId);
      if (item.CustomerUserId == itemAll.rows[index].UserId) {
        item.online = true;
        itemAll.rows.splice(index, 1);
      }
    }
  });
  groupUserListInterior.value = data.rows.MemberList;
  // console.log(groupUserListInterior.value);
  // examineList(itemAll.rows, data.rows.MemberList)
  /**外部成员 */
  let res = await proxy.$Post(
    "/DealWeChatRecord/WeChatRecordGroupMemberInfoPageList",
    {
      Page: 1,
      Rows: 1000,
      GroupInfoId: itemGroup.GroupInfoId,
      GroupName: itemGroup.GroupName,
      SendCoworker: 0,
      IsAnswer: defaultData.value.IsAnswer,
      UserId: userData.value.UserId,
    }
  );
  if (!res.Success) return;
  groupUserListExterior.value = res.rows.MemberList;
  groupAllNumber.value = res.rows.Total + data.rows.Total;
  /**统计数据 */
  let rowAll = await proxy.$Post(
    "/DealWeChatRecord/WeChatRecordDataStatistics",
    {
      GroupInfoId: itemGroup.GroupInfoId,
      GroupName: itemGroup.GroupName,
      UserId: userData.value.UserId,
      QuestionUserId: -1,
      IsAdmin: userData.value.IsAdmin,
    }
  );
  if (!rowAll.Success) return;
  console.log("统计数据", rowAll);
  statisticsAll.value = rowAll.rows;
  loadingUser.value = false;
  // groupUserList.value =
  // console.log("群组成员", groupActive.value.userList);
};
/**节流防抖 */
const GetUserMsg = (itemUser: any) => {
  debounce(ActiveUser, itemUser, 200)();
};
/**选中用户进行处理并获取聊天数据 */
const ActiveUser = async (itemUser: any) => {
  if (itemUser.QuestionUserId == 0) {
    itemUser = JSON.parse(JSON.stringify(itemUser));
    itemUser.QuestionUserId = -1;
    userActive.value.row = itemUser;
    // console.log(userActive.value);
    groupActive.value.userList.forEach(async (element: any, index: number) => {
      element.open = false;
    });
    let { rows, Success } = await proxy.$Post(
      "/DealWeChatRecord/WeChatRecordGroupMemberMsgPageList",
      {
        Page: 1,
        Rows: 15,
        GroupInfoId: itemUser.GroupInfoId,
        QuestionUserId: -1,
        IsAnswer: -1,
        UserId: userData.value.UserId,
        startTime: -1,
        endTime: -1,
        UUID: UUID.value,
      }
    );
    if (!Success) return;
    userActive.value.list = rows.Data.reverse();
    chatItemAll.value.scrollToBottom(userActive.value.QuestionUserId, 0);
    chatItemAll.value.AssignmentItem();
  } else {
    groupActive.value.userList.forEach(async (element: any, index: number) => {
      if (element.QuestionUserId == itemUser.QuestionUserId) {
        userActive.value.index = index;
        userActive.value.row = itemUser;
        if (element.NotReadCount > 0) {
          if (groupChatsList.value[groupActive.value.index].NotReadCount > 0) {
            groupChatsList.value[groupActive.value.index].NotReadCount -=
              element.NotReadCount;
          }
        }
        element.NotReadCount = 0;
        let { rows, Success } = await proxy.$Post(
          "/DealWeChatRecord/WeChatRecordGroupMemberMsgPageList",
          {
            Page: 1,
            Rows: 15,
            GroupInfoId: itemUser.GroupInfoId,
            QuestionUserId: itemUser.QuestionUserId,
            IsAnswer: defaultData.value.IsAnswer,
            UserId: userData.value.UserId,
            startTime: -1,
            endTime: -1,
            UUID: UUID.value,
          }
        );
        if (!Success) return;
        userActive.value.list = rows.Data.reverse();
        chatItemAll.value.scrollToBottom(element.QuestionUserId, 0);
        chatItemAll.value.AssignmentItem();

        element.open = true;
      } else {
        element.open = false;
      }
    });
  }
  /**统计数据 */
  let rowAll = await proxy.$Post(
    "/DealWeChatRecord/WeChatRecordDataStatistics",
    {
      GroupInfoId: userActive.value.row.GroupInfoId,
      GroupName: userActive.value.row.GroupName,
      UserId: userData.value.UserId,
      QuestionUserId: userActive.value.row.QuestionUserId,
      IsAdmin: userData.value.IsAdmin,
    }
  );
  if (!rowAll.Success) return;
  console.log("统计数据", rowAll);
  statisticsAll.value = rowAll.rows;
  // console.log(itemUser);
  // itemUser.list = [];
  /**进行用户的选中开启其余关闭 */
  //  console.log(await);
};
/**第一次获取用户后端聊天记录 */
const GetUserRecording = async (
  itemUser: any,
  startTime: number = -1,
  endTime: number = -1
) => {
  // console.log(5555);
  if (startTime == -1 && endTime == -1) {
    UUID.value = Date.now() + ",0";
  } else if (startTime != -1) {
    UUID.value = Date.now() + ",1";
  } else if (endTime != -1) {
    UUID.value = Date.now() + ",2";
  }
  let { rows, Success } = await proxy.$Post(
    "/DealWeChatRecord/WeChatRecordGroupMemberMsgPageList",
    {
      Page: 1,
      Rows: 15,
      GroupInfoId: itemUser.GroupInfoId,
      QuestionUserId: itemUser.QuestionUserId,
      IsAnswer: defaultData.value.IsAnswer,
      UserId: userData.value.UserId,
      startTime: startTime,
      endTime: endTime,
      UUID: UUID.value,
    }
  );
  if (!Success) return;
};
/**触发到顶部获取更老的聊天记录*/
const GetOldData = async (row: any) => {
  /**找到需要加载数据的用户 */
  console.log(userActive.value);

  let list = userActive.value.list;
  let { rows, Success } = await proxy.$Post(
    "/DealWeChatRecord/WeChatRecordGroupMemberMsgPageList",
    {
      Page: 1,
      Rows: 15,
      GroupInfoId: userActive.value.row.GroupInfoId,
      QuestionUserId: userActive.value.row.QuestionUserId,
      IsAnswer: defaultData.value.IsAnswer,
      UserId: userData.value.UserId,
      startTime: -1,
      endTime: list[0].TimeStamp,
      UUID: UUID.value,
    }
  );
  if (!Success) return;
  userActive.value.list = rows.Data.reverse().concat(userActive.value.list);
  console.log(rows);
  if (rows.Data.length != 0) {
    chatItemAll.value.scrollToBottom(0, 0, 800);
  }
  // GetUserRecording(
  //   groupActive.value.userList[userActive.value.index],
  //   -1,
  //   list[0].TimeStamp
  // );
  // let user: any = await getChatHistory(
  //   groupActive.value.userList[userActive.value.index].QuestionUserId,
  //   groupActive.value.GroupInfoId
  // );
  // console.log(list);

  // console.log(list[0].TimeStamp);
  // if (list.length == user.list.length) {
  //   /**去线上拿数据 */
  //   GetUserRecording(
  //     groupActive.value.userList[userActive.value.index],
  //     -1,
  //     list[0].TimeStamp
  //   );
  // } else if (user.list.length - list.length >= 15) {
  //   //  groupChatsList.value[groupActive.value.index].userList[
  //   //   userActive.value.index
  //   // ].list =
  //   /**数据还很多 */

  //   groupActive.value.userList[userActive.value.index].list = user.list
  //     .slice(
  //       user.list.length - list.length - 15,
  //       user.list.length - list.length
  //     )
  //     .concat(list);
  //   chatItemAll.value.scrollToBottom(
  //     groupActive.value.userList[userActive.value.index].QuestionUserId,
  //     0,
  //     800
  //   );
  //   // console.log("总数据", groupChatsList.value, groupActive.value);
  // } else if (user.list.length - list.length >= 0) {
  //   groupActive.value.userList[userActive.value.index].list = user.list
  //     .slice(0, user.list.length - list.length)
  //     .concat(list);
  //   chatItemAll.value.scrollToBottom(
  //     groupActive.value.userList[userActive.value.index].QuestionUserId,
  //     0,
  //     800
  //   );
  // }
};
/**删除数据库 */
const Database = async () => {
  deleteDatabase(userData.value.UserId);
};
const CloseWs = () => {
  closeWebSocket();
  // store.dispatch("websocket/disconnect");
};

const deleteData = () => {};
// 新增
const newAdd = () => {};
/**获取个人信息 */
const GetUser = async () => {
  // 获取查询参数
  const queryString = window.location.search;
  // 创建 URLSearchParams 对象
  const params = new URLSearchParams(queryString);
  // 获取 chatuser 的值
  const chatuser = params.get("chatuser");
  let { rows, Success } = await proxy.$Post(
    "/DealWeChatRecord/LoginWeChatRecord",
    {
      Token: chatuser,
    }
  );
  if (!Success) return;
  // console.log(rows);
  userData.value = rows;
  GetGroundList();
};
GetUser();
ConnectMsg();
GetWsMessage();
</script>
<style lang="scss" src="./index.scss">
</style>